'''
Author: goog
Date: 2021-12-13 16:45:46
LastEditTime: 2022-01-13 16:08:58
LastEditors: goog
Description: 下段检测只在10号摄像头检测
FilePath: /chengdu/TensorRT20220110/DetectionZM/LBZ/LBZ.py
Time Limit Exceeded!
'''
import json
import os
import cv2
import torch
import numpy as np
from PIL import Image
from torchvision import transforms
from torchvision.models import resnet18
from sklearn.decomposition import PCA


def lbz(cfg, item, image, barcode, net, visualization=True):
    if 'lbyj' in item.keys():
        tmp = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2RGB)
        xmin, ymin, xmax, ymax, conf = item['lbyj'][0]
        sx, sy = xmin, ymin
        roi1 = tmp[sy: sy+100, sx: sx+100, :]
        sx, sy = xmin+100, ymin+100
        roi2 = tmp[sy: sy+100, sx: sx+100, :]
        sx, sy = xmin+200, ymin+200
        roi3 = tmp[sy: sy+100, sx: sx+100, :]
        
        _, color = net.clsLBZColor(roi1, roi2, roi3)
        print('LBZ:', color)
        # load config
        defect = "LBZ"
        config_path = os.path.join(cfg['abs_dir'], 'DetectionZM/'+defect+'/'+defect+'.json')
        with open(config_path, 'r') as fp:
            config = json.load(fp)    
                
        if barcode[:3] in ['C50', 'C51', 'C52', 'C59', 'C60', 'C54', 'C55', 'H1H', 'H2H', 'H3H']:
            # 黑色
            barcode = 'C50'+barcode[3:]
            return config[barcode]['label']==color
        elif barcode[:3] in ['C53', 'C61']:
            # 灰色
            barcode = 'C53'+barcode[3:]
            return config[barcode]['label']==color
        elif barcode[:3] in ['C56', 'C57', 'C58']:
            # 钢琴漆 other
            barcode = 'C56'+barcode[3:]
            return config[barcode]['label']==color
        else:
            print('LBZ error')
            return False
        return True
    else:
        return False
#     # 设备
#     device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

#     # 网络       
#     if classif_net == None:
#         classif_net = resnet18(pretrained=True).to(device)
#         classif_net.eval()

#     # 读配置文件
#     defect = 'LBZ'    
#     abs_dir = cfg['abs_dir']
#     config_path = os.path.join(abs_dir, 'DetectionZM/'+defect+'/'+defect+'.json')
#     feature_list = []
#     with open(config_path) as json_file:
#         config = json.load(json_file)
#         if barcode not in config.keys():
#             barcode = 'C50'+barcode[3:]
#         c =  config[barcode]
#         if c['label'] == defect.lower():
#             points = c['points']
#             image4 = image[c['position']]

#             roi_list = []
#             for point in points.values():
#                 ref = image4[point[0]:point[0]+point[2], point[1]:point[1]+point[3], :]
#                 roi_list.append(ref)
#                 if visulization:
#                     cv2.rectangle(image4, (point[0], point[1]), (point[0]+point[2], point[1]+point[3]), color=(0, 255, 255), thickness=5)
#                     cv2.putText(image4, defect, (point[0], point[1] - 2), 0, 3 / 3, [225, 255, 255], thickness=3, lineType=cv2.LINE_AA)
            
#             if visulization:
#                 cv2.imwrite(os.path.join(abs_dir, 'Test', defect.upper()+".png"), image4)
#             image_transform = transforms.Compose([
#                 transforms.ToTensor(),
#                 transforms.Normalize(mean=(0.485, 0.456, 0.406),
#                                  std=(0.229, 0.224, 0.225))
#             ])
            
#             for ind, img in enumerate(roi_list):
#                 # print(img.shape)
#                 I_img = Image.fromarray(img)
#                 t_img = image_transform(I_img)
#                 t_img = t_img.unsqueeze(0)
#                 t_img = t_img.to(device)
#                 with torch.no_grad():
#                     feature = classif_net(t_img)
#                     f_n = feature.data.cpu().numpy()
#                     feature_list.append(f_n)
#         else:
#             return False 
#     defect_feature_path =  os.path.join(abs_dir, 'DetectionZM', defect, barcode+'.npy')              
#     # 保存特征    
#     if is_save:
#         # feature_dict = {}
#         # for ind, ft in enumerate(feature_list):
#         #     feature_dict[str(ind+1)] = ft 
#         feature_np = np.array(feature_list)
#         np.save(defect_feature_path, feature_np)
#     else:
#         # 加载特征
#         tem_feature = np.load(defect_feature_path, allow_pickle=True)  
#         fl = np.array(feature_list) 
#         tf = np.array(tem_feature)    
#         sub= np.mean(np.abs(fl-tf), axis=-1)
#         if np.sum(sub)>20:
#             return False
#         else:
#             return True
    
#     return False   





# if __name__ == "__main__":
#     ref = cv2.imread('./Templates/C50/FR-L/169.254.7.10.jpg')
#     ref = cv2.cvtColor(ref, cv2.COLOR_BGR2RGB)
           
#     lbz(ref, "C50FR-L", is_save=True)

            
            

